package controller

import (
	"context"
	"encoding/json"
	"fmt"

	tableComm "gitee.com/klein-x/biz/model/mysql/table/comm"
	tableSystem "gitee.com/klein-x/biz/model/mysql/table/system"
	"gitee.com/klein-x/biz/xutils"
)

const (
	SYS_DB_ERR = 9900
)

func GetAllSystem(ctx context.Context) ([]SystemInfo, error) {
	tableSystem, err := tableSystem.HomeGetByAll()
	if err != nil {
		return nil, xutils.Error(SYS_DB_ERR, err)
	}

	if tableSystem == nil {
		return nil, nil
	}

	var sysInfo []SystemInfo
	for _, sys := range *tableSystem {
		var info SystemInfo
		info.SystemID = sys.ID
		info.SystemName = sys.Name
		sysInfo = append(sysInfo, info)
	}

	return sysInfo, nil
}

func GetSystemBanners(ctx context.Context, systemId string) ([]string, error) {
	banners, err := tableSystem.BannerGetByKey(systemId)
	if err != nil || banners == nil {
		return nil, xutils.Error(SYS_DB_ERR, err)
	}
	if banners == nil {
		return nil, nil
	}
	return banners, nil
}

func GetSystemGoodsSummarys(ctx context.Context, systemId string) ([]GoodsSummary, error) {
	goodss, err := tableSystem.GoodsGetByID(systemId)
	if err != nil {
		return nil, xutils.Error(SYS_DB_ERR, err)
	}

	if goodss == nil {
		return nil, nil
	}

	goodsDetails, err := tableComm.GoodsGetByKeys(goodss)
	if err != nil {
		return nil, xutils.Error(SYS_DB_ERR, err)
	}

	if goodsDetails == nil {
		return nil, nil
	}

	var summarys []GoodsSummary
	for _, detail := range *goodsDetails {
		var summary GoodsSummary
		summary.ID = detail.GoodsID
		summary.Name = detail.Name
		summary.Summary = json.RawMessage(detail.Summary)
		summary.Thumbnail = detail.Thumbnail
		summary.BuyerCount = detail.BuyerCount
		summary.Price = detail.Price

		summarys = append(summarys, summary)
	}
	return summarys, nil
}

func GetGoodsDetail(ctx context.Context, goodsId string) (*GoodsDetail, error) {
	tableGoods, err := tableComm.GoodsGetByKey(goodsId)
	if err != nil {
		return nil, xutils.Error(SYS_DB_ERR, err)
	}

	if tableGoods == nil {
		return nil, nil
	}

	var detailInfo GoodsDetail
	detailInfo.ID = tableGoods.GoodsID
	detailInfo.Name = tableGoods.Name

	detailInfo.Summary = json.RawMessage(tableGoods.Summary)
	detailInfo.Thumbnail = tableGoods.Thumbnail

	detailInfo.PageInfo = json.RawMessage(tableGoods.PageInfo)
	detailInfo.BuyerCount = tableGoods.BuyerCount
	detailInfo.Price = tableGoods.Price
	detailInfo.PublishTime = *tableGoods.PublishedAt

	// 将秒数转换为时间

	days := tableGoods.Duration / (24 * 60 * 60)
	hours := tableGoods.Duration % (24 * 60 * 60) / (60 * 60)
	minutes := tableGoods.Duration % (60 * 60) / (60)
	seconds := tableGoods.Duration % (60)
	detailInfo.Duration = fmt.Sprintf("%d天%d小时%d分钟%d秒", days, hours, minutes, seconds)

	detailInfo.ChapterID = tableGoods.ChapterID

	return &detailInfo, nil
}
